<template>
  <div class="layout">
    <Layout>
      <Header :style="{backgroundColor: '#fff', paddingLeft: 0, paddingRight: 0}">
        <Menu ref="topMenu" mode="horizontal" theme="primary" :active-name="activeMenu" :style="{height: '100%'}" @on-select="handleSelect">
          <div class="layout-logo"></div>
          <div class="layout-nav">
            <MenuItem v-for="item in menus" :name="item.id" :key="item.id">
            <Icon :type="item.icon || 'md-apps'"></Icon>{{item.name}}</MenuItem>
            <Dropdown @on-click="handleLogout" :style='{ marginLeft: "20px" }'>
              <Button type="primary">
                设置
                <Icon type="ios-arrow-down"></Icon>
              </Button>
              <DropdownMenu slot="list">
                <DropdownItem>设置1</DropdownItem>
                <DropdownItem>设置2</DropdownItem>
                <DropdownItem disabled>设置3</DropdownItem>
                <DropdownItem divided @click="handleLogout">退出</DropdownItem>
              </DropdownMenu>
            </Dropdown>
          </div>
        </Menu>
      </Header>
      <Layout :style="{height: contentHeight}">
        <Sider :class="(!subMenus || subMenus.length === 0) && 'hide-sider'" :default-collapsed="!subMenus || subMenus.length === 0" hide-trigger :style="(!subMenus || subMenus.length === 0) ? {width: 0, maxWidth: 0, minWidth: 0, flex: 0} : {background: '#fff', height: '100%', overflow: 'auto'}">
          <Menu ref="secondMenu" :active-name="activeSubMenu" theme="light" width="auto" :open-names="[openMenu]" @on-open-change="handleOpenChange" accordion>
            <Submenu v-for="item in subMenus" v-if="item.childrenCount > 0" :name="item.id" :key="item.id">
              <template slot="title">
                <Icon :type="item.icon || 'md-apps'"></Icon>
                {{item.name}}
              </template>
              <MenuItem v-for="sItem in item.children" :name="sItem.id" :key="sItem.id" :to="item.uri">{{sItem.name}}</MenuItem>
            </Submenu>
            <MenuItem v-for="item in subMenus" v-if="item.childrenCount === 0" :name="item.id" :key="item.id" :to="item.uri">
            <Icon :type="item.icon || 'md-apps'"></Icon>{{item.name}}
            </MenuItem>
          </Menu>
        </Sider>
        <Layout :style="{padding: '0 24px 24px', height: '100%', overflow: 'auto'}">
          <!-- <Breadcrumb :style="{margin: '24px 0'}">
            <BreadcrumbItem>Home</BreadcrumbItem>
            <BreadcrumbItem>Components</BreadcrumbItem>
            <BreadcrumbItem>Layout</BreadcrumbItem>
          </Breadcrumb>
          <Content :style="{padding: '24px', minHeight: '580px', background: '#fff'}">
            Content
          </Content> -->
          <Content>
            <router-view></router-view>
          </Content>
        </Layout>
      </Layout>
      <Footer :style="{padding: '4px 24px'}">2018</Footer>
    </Layout>
  </div>
</template>

<script>
// import axios from 'axios'

export default {
  name: 'app',
  data () {
    return {
      activeMenu: '',
      activeSubMenu: '',
      openMenu: '',
      subMenus: [],
      contentHeight: '',
      userId: ''
    }
  },
  components: {
  },
  computed: {
    menus () {
      return this.$store.state.menu.top
    },
    isLogin () {
      return this.$store.state.client.isLogin
    }
  },
  created () {
    console.log('app created')
    // 获取 token
    const token = this.$storage.getItem('token')
    console.log('token', token)
    if (!token) {
      this.$router.path !== '/login' && this.$router.replace('/login')
      return
    }
    this.$store.dispatch(`menu/getTree`, {
      cb: this.setMenuStatus
    })
    const userId = this.$storage.getItem('userId')
    this.$store.dispatch(`premission/getMyList`, userId)
    /* this.findMenuTree()
    this.isLogin = true */
  },
  mounted () {
    console.log('app mounted')
    // 动态设置背景图的高度为浏览器可视区域高度

    // 首先在Virtual DOM渲染数据时，设置下背景图的高度．
    this.contentHeight = `${document.documentElement.clientHeight - 64 - 29}px`
    // 然后监听window的resize事件．在浏览器窗口变化时再设置下背景图高度．
    const that = this
    window.onresize = function temp () {
      that.clientHeight = `${document.documentElement.clientHeight - 64 - 29}px`
    }
  },
  updated () {
    console.log('app updated')
    /* if (this.$router.path === '/') {
      this.findMenuTree()
    } */
  },
  watch: {
    isLogin (val) {
      if (val) {
        this.$store.dispatch(`menu/getTree`, {
          cb: this.setMenuStatus
        })
        const userId = this.$storage.getItem('userId')
        this.$store.dispatch(`premission/getMyList`, userId)
      }
    }
  },
  methods: {
    handleLogout () {
      this.$Modal.confirm({
        title: '退出登录',
        content: '<p>将退出系统并跳转到登陆页面.</p>',
        onOk: () => {
          this.$storage.removeItem('token')
          // axios.defaults.headers.common['Authorization'] = ''
          this.$storage.removeItem('userId')
          this.$router.replace('/login')
        },
        onCancel: () => {
          console.log('cancel logout')
        }
      })
    },
    handleSelect (name) {
      this.activeMenu = name
      for (let i in this.menus) {
        if (this.menus[i].id === name && this.menus[i].childrenCount === 0) {
          this.$router.push(this.menus[i].uri)
          break
        }
      }
      this.$store.dispatch(`menu/getTree`, {
        cb: this.setSubMenuStatus,
        parentId: name
      })
    },
    handleOpenChange (name) {
      this.openMenu = name
      this.$store.dispatch(`menu/getTree`, {
        cb: this.setSubMenuChildren,
        parentId: name[0]
      })
    },
    setSubMenuChildren (result) {
      for (let i in this.subMenus) {
        if (this.subMenus[i].id === this.openMenu[0]) {
          this.subMenus[i]['children'] = result
          break
        }
      }
      this.$nextTick(() => {
        this.$refs.secondMenu.updateOpened()
      })
    },
    setSubMenuStatus (result) {
      this.subMenus = result
      for (let i in this.subMenus) {
        if (this.subMenus[i].uri === this.$route.path) {
          this.activeSubMenu = this.subMenus[i].id
          this.$router.push(this.subMenus[i].uri)
          break
        } else if (this.subMenus[i].uri.length > 1 && this.$route.path.indexOf(this.subMenus[i].uri) > -1) {
          if (this.subMenus[i].children && this.subMenus[i].children.length > 0) {
            // 打开三级菜单
            this.openMenu = this.subMenus[i].id
            this.$store.dispatch(`menu/getTree`, {
              cb: this.setSubMenuChildren,
              parentId: this.openMenu
            })
          } else {
            this.activeSubMenu = this.subMenus[i].id
            this.$router.push(this.subMenus[i].uri)
          }
          break
        } else {
          this.activeSubMenu = ''
          this.openMenu = ''
        }
      }
      this.$nextTick(() => {
        this.$refs.secondMenu.updateOpened()
        this.$refs.secondMenu.updateActiveName()
      })
    },
    setMenuStatus () {
      // console.log('this.$route.path', this.$route.path)
      let isPath = false
      for (let i in this.menus) {
        if (this.menus[i].uri === this.$route.path) {
          this.activeMenu = this.menus[i].id
          // this.$router.push(this.menus[i].uri)
          this.subMenus = []
          isPath = true
          break
        } else if (this.menus[i].uri.length > 1 && this.$route.path.indexOf(this.menus[i].uri) > -1) {
          this.activeMenu = this.menus[i].id
          // 这里自动生成二级菜单
          this.$store.dispatch(`menu/getTree`, {
            cb: this.setSubMenuStatus,
            parentId: this.activeMenu
          })
          isPath = true
          break
        }
      }
      if (isPath) {
        this.$nextTick(() => {
          // this.$refs.topMenu.updateOpened()
          this.$refs.topMenu.updateActiveName()
        })
      } else {
        // 没有匹配就直接跳转
        if (this.menus.length > 0) {
          this.$router.push(this.menus[0].uri)
        }
        // this.subMenus = []
      }
    }
  }
}
</script>

<style>
html,
body {
  width: 100%;
  height: 100%;
}
.layout {
  /* border: 1px solid #d7dde4; */
  background: #f5f7f9;
  position: relative;
  /* border-radius: 4px; */
  overflow: hidden;
  height: 100%;
}
.layout-logo {
  width: 100px;
  height: 30px;
  background: #266eff;
  border-radius: 3px;
  float: left;
  position: relative;
  top: 15px;
  left: 20px;
}
.layout-nav {
  display: flex;
  justify-content: flex-end;
  margin: 0 auto;
  margin-right: 20px;
}
.hide-sider {
  width: 0;
  max-width: 0;
  min-width: 0;
  flex: 0;
}
</style>
